import config from "@/config"
import tool from '@/utils/tool'

/* 挂载 websocket */
import WebsocketHeartbeatJs from 'websocket-heartbeat-js';
let websocketHeartbeatJs = new WebsocketHeartbeatJs({
	url: config.WEB_SOCKET + "?token=" + tool.cookie.get("TOKEN")
});
websocketHeartbeatJs.onopen = function() {
	console.log('connect success');
	websocketHeartbeatJs.send('hello server');
}
websocketHeartbeatJs.onmessage = function(e) {
	console.log(`onmessage: ${e.data}`);
}
websocketHeartbeatJs.onreconnect = function() {
	console.log('reconnecting...');
}
websocketHeartbeatJs.retry = function() {
	if (config.WEB_SOCKET) {
		var url = config.WEB_SOCKET + "?token=" + tool.cookie.get("TOKEN");
		if (this.opts.url !== url) {
			this.opts.url = config.WEB_SOCKET + "?token=" + tool.cookie.get("TOKEN");
			this.ws.close()
			setTimeout(() => {
				this.reconnect();
			}, 200)
		}
	}
}
if (!config.WEB_SOCKET) {
	websocketHeartbeatJs.close();
}

export default {
	install: (app) => {
		websocketHeartbeatJs.onmessage = function(e) {
			if (e !== 'heartbeat') {
				try {
					app.config.globalProperties.$mitt.emit('websocket', JSON.parse(e))
				} catch (e) {

				}
			}
		}
		app.config.globalProperties.$websocket = websocketHeartbeatJs
	}
}
